package com.huibao.hulibao.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.apkfuns.logutils.LogUtils;
import com.example.zhouwei.library.CustomPopWindow;
import com.huibao.hulibao.R;
import com.huibao.hulibao.constant.GlobalConstants;
import com.huibao.hulibao.entity.AllLoginEntity;
import com.huibao.hulibao.entity.BindNumberEntity;
import com.huibao.hulibao.entity.LoginEntity;
import com.huibao.hulibao.utils.AppManager;
import com.huibao.hulibao.utils.DialogUtils;
import com.huibao.hulibao.utils.MyUtils;
import com.huibao.hulibao.utils.PreUtils;
import com.huibao.hulibao.utils.T;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * Created by lizhaoyong on 2018/5/9.
 */
public class LoginActivity extends BaseActivity {

    @BindView(R.id.rl_bind_xuliehao)
    RelativeLayout rl_bind_xuliehao;
    @BindView(R.id.iv_login_logo)
    ImageView iv_login_logo;
    @BindView(R.id.tv_login)
    TextView tv_login;
    @BindView(R.id.et_login_username)
    EditText et_login_username;
    @BindView(R.id.et_login_password)
    EditText et_login_password;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.fl_main)
    FrameLayout fl_main;
    @BindView(R.id.iv_bg)
    ImageView iv_bg;
    @BindView(R.id.tv_login_title)
    TextView tv_login_title;


    private EditText et_bind_number;
    private TextView tv_bind_number_confirm;
    // 绑定序列号返回的对象
    private BindNumberEntity bne;
    // 登录返回的对象
    private LoginEntity le;
    // 扫码返回结果
    private int REQUEST_CODE = 20;

    private Dialog myDialog;

    private String loginName;


    // 用户登录
    @OnClick(R.id.tv_login)
    public void userLogin() {
        final String username = MyUtils.replaceBlank(et_login_username.getText().toString());
        String password = MyUtils.replaceBlank(et_login_password.getText().toString());
        if (username == null || username.equals("")) {
            T.show(getApplicationContext(), getString(R.string.namenotnull), 0);
            return;
        }

        if (password == null || password.equals("")) {
            T.show(getApplicationContext(), getString(R.string.mimabunengweikong), 0);
            return;
        }

        // LogUtils.d("jpush_id = " + String.valueOf(JPushInterface.getRegistrationID(getApplicationContext())));
        showDialog();
        // RequestParams params = new RequestParams("http://test7.usoft.me:7000/JWServices.aspx");
        RequestParams params = new RequestParams(GlobalConstants.URL);
        // LogUtils.d("url = " + GlobalConstants.URL);
        params.setCacheMaxAge(0);
        JSONObject object = new JSONObject();
        try {
            object.put("key", username);
            object.put("pwd", password);
            object.put("device", "Android");
            object.put("token", String.valueOf(JPushInterface.getRegistrationID(getApplicationContext())));
            object.put("v", GlobalConstants.APP_VERSION);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("q", GlobalConstants.URL_LOGIN + object.toString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                closeDialog();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    LogUtils.d("result = " + jsonObject);
                    if (jsonObject.toString().contains("\"State\"" + ":" + "\"" + GlobalConstants.SUCCESS_CODE + "\"")) {
                        le = GlobalConstants.gson.fromJson(jsonObject.toString(), LoginEntity.class);
                        // 存储用户名
                        le.Message.LoginName = et_login_username.getText().toString();
                        //成功
                        if (le.State.equals(GlobalConstants.SUCCESS_CODE)) {
                            T.show(getApplicationContext(), getString(R.string.loginsuccess), 0);
                            // 序列号对象到本地
                            PreUtils.saveObject(getApplicationContext(), "LoginEntity", le);
                            // 系统区分
                            PreUtils.saveObject(getApplicationContext(), "SysType", le.Message.SysType);

                            // 获取本地存储的用户登录集合
                            AllLoginEntity ale = (AllLoginEntity) PreUtils.getObject(getApplicationContext(), "AllLoginEntity");
                            if (ale == null) {
                                ale = new AllLoginEntity();
                                ArrayList<LoginEntity> al = new ArrayList<LoginEntity>();
                                al.add(le);
                                ale.setAll_login(al);
                                // 存储在本地
                                PreUtils.saveObject(getApplicationContext(), "AllLoginEntity", ale);
                            } else {
                                ArrayList<LoginEntity> al = ale.getAll_login();
                                boolean b = false;
                                for (int i = 0; i < al.size(); i++) {
                                    if (al.get(i).Message.LoginName.equals(le.Message.LoginName)) {
                                        b = true;
                                    }
                                }
                                // 如果没是没有登录过的就记录
                                if (!b) {
                                    if (al.size() >= 6) {
                                        al.remove(0);
                                    }
                                    al.add(le);
                                    ale.setAll_login(al);
                                    // 存储在本地
                                    PreUtils.saveObject(getApplicationContext(), "AllLoginEntity", ale);
                                }
                            }

                            // 存储最对6个对象
                            // LogUtils.d("session = " + le.toString());
//                            PreUtils.setParam(getApplicationContext(), GlobalConstants.SP_SESSION, le.Message.Session);
//                            PreUtils.setParam(getApplicationContext(), GlobalConstants.SP_STORENAME, le.Message.StoreName);
//                            PreUtils.setParam(getApplicationContext(), GlobalConstants.SP_USERID, le.Message.UserId);
//                            PreUtils.setParam(getApplicationContext(), GlobalConstants.SP_USERNAME, le.Message.UserName);
//                            PreUtils.setParam(getApplicationContext(), GlobalConstants.SP_STOREID, le.Message.StoreId);
//                            PreUtils.setParam(getApplicationContext(), GlobalConstants.SP_LOGIN_USERNAME, username);
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("LoginEntity", le);//序列化
                            intent.putExtras(bundle);//发送数据
                            startActivity(intent);
                            finish();
                        }
                    } else {
                        // 失败
                        BindNumberEntity b = GlobalConstants.gson.fromJson(jsonObject.toString(), BindNumberEntity.class);
                        T.show(getApplicationContext(), b.getMessage(), 0);
                        return;
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                closeDialog();
            }

            @Override
            public void onFinished() {
                closeDialog();
            }
        });

    }


    // 显示绑定序列号的页面
    @OnClick(R.id.rl_bind_xuliehao)
    public void showBindPop() {
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();

        final CustomPopWindow popWindow = new CustomPopWindow.PopupWindowBuilder(LoginActivity.this)
                .setView(R.layout.popwindow_bind_number)
                .setFocusable(true)
                .size((int) (width * 0.8), 800)
                .setOutsideTouchable(true)
                // pop消失监听
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {

                    }
                })
                .create();
        popWindow.showAtLocation(fl_main, Gravity.CENTER, 0, 0);
        ImageView iv_scan = (ImageView) popWindow.getPopupWindow().getContentView().findViewById(R.id.iv_scan);
        iv_scan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 扫码
                scan();

            }
        });


        et_bind_number = (EditText) popWindow.getPopupWindow().getContentView().findViewById(R.id.et_input_number);
        tv_bind_number_confirm = (TextView) popWindow.getPopupWindow().getContentView().findViewById(R.id.tv_bind_number_confirm);
        tv_bind_number_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 设置显示位置
                String license = et_bind_number.getText().toString();
                if (license == null || license.equals("")) {
                    T.show(getApplicationContext(), getString(R.string.bangdingxuliehaobunengweikong), 0);
                    return;
                }
                // 判断网络是否可用
                // 显示访问网络对话框
                showDialog();
                // 绑定序列号的支持
                RequestParams params = new RequestParams(GlobalConstants.BIND_URL);
                // 不缓存
                params.setCacheMaxAge(0);
                params.addBodyParameter("q", GlobalConstants.URL_BIND_NUMBER + MyUtils.encode(System.currentTimeMillis(), license));

                x.http().post(params, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        closeDialog();
                        JSONObject jsonObject;
                        try {
                            // 转为json
                            jsonObject = new JSONObject(result);
                            LogUtils.d("result = " + jsonObject.toString());
                            bne = GlobalConstants.gson.fromJson(jsonObject.toString(), BindNumberEntity.class);
                            if (bne.getState().equals(GlobalConstants.SUCCESS_CODE)) {
                                T.show(getApplicationContext(), getString(R.string.BindSuccess), 0);
                                // 清除本地登录记录
                                PreUtils.saveObject(getApplicationContext(), "AllLoginEntity", null);
                                // 关闭POP
                                popWindow.dissmiss();
                                // 存放返回访问地址
                                MyUtils.saveBindInterface(getApplicationContext(), bne.getMessage());
                                String name = (String) PreUtils.getParam(getApplicationContext(), GlobalConstants.SP_NAME, "");
                                tv_name.setText(name);
                                // LogUtils.d("msg = " + bne.getMessage());
                            } else {
                                T.show(getApplicationContext(), bne.getMessage(), 0);
                            }
                            //解析result
//                            LogUtils.d("result = " + jsonObject.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        closeDialog();
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {
                        closeDialog();
                    }

                    @Override
                    public void onFinished() {
                        closeDialog();
                    }
                });
            }
        });

        popWindow.showAsDropDown(iv_login_logo, -300, 30);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        String sysType = (String) PreUtils.getObject(getApplicationContext(), "SysType");
        if (sysType != null && sysType.equals("ck")) {
            iv_bg.setImageResource(R.mipmap.login_logo_ck);
            tv_login_title.setText("让工作变得简单");
        }
        
        loginName = getIntent().getStringExtra("loginName");
        if (loginName != null && !loginName.equals("")) {
            et_login_username.setText(loginName);
        }

        // 初始化二维码扫描
        ZXingLibrary.initDisplayOpinion(getApplicationContext());
        // 防止在控件未初始化前崩溃的情况
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // 如果用户没有绑定序列号弹出序列号绑定
                if (MyUtils.isUserBindNumber(getApplicationContext()) == false) {
                    showBindPop();
                }
            }
        }, 500);

        String name = (String) PreUtils.getParam(getApplicationContext(), GlobalConstants.SP_NAME, "");
        tv_name.setText(name);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                           int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = 105)
    public void doSomething() {
        T.show(getApplicationContext(), getString(R.string.xiangjiquanxiankaiqi), 0);
    }

    @PermissionFail(requestCode = 105)
    public void doFailSomething() {
        T.show(getApplicationContext(), getString(R.string.xiangjiquanxiandakaishibai), 0);
    }

    public void scan() {
        if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            // 没有权限，申请权限。
            // 请求开启相机权限
            PermissionGen.needPermission(LoginActivity.this, 105,
                    new String[]{
                            Manifest.permission.CAMERA}
            );
        } else {
            // 有权限了
            Intent intent = new Intent(getApplicationContext(), CaptureActivity.class);
            startActivityForResult(intent, REQUEST_CODE);
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    public void showDialog() {
        myDialog = DialogUtils.createLoadingDialog(LoginActivity.this, getResources().getString(R.string.jiazaizhong));
    }

    public void closeDialog() {
        DialogUtils.closeDialog(myDialog);
    }

    // 二维码扫描结果显示
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    et_bind_number.setText(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    T.show(getApplicationContext(), getString(R.string.jiexierweimashibai), 0);
                }
            }
        }
    }


    @Override
    public void onBackPressed() {
        AppManager.getAppManager().AppExit(this);
        finish();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (MyUtils.isShouldHideInput(v, ev)) {
                if (MyUtils.hideInputMethod(this, v)) {
                    return true; //隐藏键盘时，其他控件不响应点击事件==》注释则不拦截点击事件
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }
}
